package com.ys.shardingjdbcdemo.config;

import com.ys.shardingjdbcdemo.goods.sharding.GoodsTableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.NoneShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class DataSourceConfig {
    @Autowired
    private Database0Config database0Config;

    @Autowired
    private Database1Config database1Config;

    @Autowired
    private GoodsTableRuleConfiguration goodsTableRuleConfiguration;

    @Bean
    public DataSource getDataSource() throws SQLException {
        // 分库设置
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put(database0Config.getDatabaseName(), database0Config.createDataSource());
        dataSourceMap.put(database1Config.getDatabaseName(), database1Config.createDataSource());

        // 分表设置, 大致思想是将查询虚拟表Goods根据一定条件映射到真实表中去
        ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
        shardingRuleConfiguration.getTableRuleConfigs().add(goodsTableRuleConfiguration.getGoodsTableRuleConfiguration());
        shardingRuleConfiguration.setDefaultDatabaseShardingStrategyConfig(new NoneShardingStrategyConfiguration());
        shardingRuleConfiguration.setDefaultTableShardingStrategyConfig(new NoneShardingStrategyConfiguration());
        return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfiguration, new Properties());
    }

    @Bean
    public KeyGeneratorConfiguration getKeyGeneratorConfig() {
        return new KeyGeneratorConfiguration("SNOWFLAKE", "goods_id");
    }
}